package ua.edu.nuos.jeetraining2012.cms.util.oauth;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.scribe.builder.api.VkontakteApi;
import org.scribe.exceptions.OAuthException;
import org.scribe.model.OAuthConfig;
import org.scribe.model.SignatureType;
import org.scribe.model.Token;
import org.scribe.up.credential.OAuthCredential;
import org.scribe.up.profile.UserProfile;
import org.scribe.up.provider.BaseOAuth20Provider;
import org.scribe.up.provider.BaseOAuthProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class VkontakteProvider extends BaseOAuth20Provider {

    protected String fields = "uid,first_name,last_name,nickname,screen_name,sex,bdate,city,country,timezone,photo,photo_medium,photo_big,has_mobile,rate,contacts,education,online,counters";
    protected String scope = "notify";
    protected String userId;

    /**
     * @{inheritDoc}
     */
    @Override
    protected BaseOAuthProvider newProvider() {
        final VkontakteProvider newProvider = new VkontakteProvider();
        return newProvider;
    }

    /**
     * @{inheritDoc}
     */
    @Override
    protected void internalInit() {
        this.service = new VKontakteServiceImpl(new VkontakteApi(), new OAuthConfig(key, secret, callbackUrl, SignatureType.Header, scope, null));
    }

    /**
     * @{inheritDoc}
     */
    @Override
    protected String getProfileUrl() {
        if ((userId == null) || (userId.isEmpty())) {
            throw new OAuthException("No VK.com userId is available");
        }
        return String.format("https://api.vk.com/method/users.get?uids=%s&fields=%s", userId, fields);  //To change body of implemented methods use File | Settings | File Templates.
    }


    /**
     * @{inheritDoc}
     */
    @Override
    protected UserProfile extractUserProfile(String body) {
        final VkontakteProfile profile = new VkontakteProfile();
        Logger log = LoggerFactory.getLogger(getClass());
        if ((body == null) || (body.isEmpty()))
            return profile;
        try {
            JSONParser parser = new JSONParser();
            JSONObject jo = (JSONObject) parser.parse(body);
            JSONArray ja = (JSONArray) jo.get("response");
            jo = (JSONObject) ja.get(0);
            VkontakteAttributesDefinition attr = new VkontakteAttributesDefinition();
            profile.setId(jo.get("uid"));
            for (final String attribute : attr.getPrincipalAttributes()) {
                profile.addAttribute(attribute, jo.get(attribute));
            }
        } catch (Exception e) {
            log.debug("extractUserProfile() exception : Body: {} , Message: {}", body, e.getMessage());
            return new VkontakteProfile();
        }
        return profile;
    }


    /**
     * @{inheritDoc}
     */
    @Override
    protected Token getAccessToken(final OAuthCredential credential) {
        Token t = super.getAccessToken(credential);
        userId = ((VKontakteServiceImpl) this.service).getUserId();
        return t;
    }
}
